﻿using System.Windows;
using System.Windows.Controls;

namespace LiveTiss.Guias.UserControls
{
    public partial class BooleanPicker : UserControl
    {
        public static readonly DependencyProperty SelectedValueProperty = DependencyProperty.Register("SelectedValue",
            typeof(bool?), typeof(BooleanPicker), new PropertyMetadata(SelectedValuePropertyChanged));

        public bool? SelectedValue
        {
            get { return (bool?)GetValue(SelectedValueProperty); }
            set { SetValue(SelectedValueProperty, value); }
        }

        public event RoutedPropertyChangedEventHandler<bool?> SelectedValueChanged;

        private static void SelectedValuePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            BooleanPicker myControl = d as BooleanPicker;

            if (myControl != null)
            {
                if (e.NewValue != null)
                {
                    if ((bool)e.NewValue)
                    {
                        myControl.cbxBoolean.SelectedIndex = 1;
                    }
                    else
                    {
                        myControl.cbxBoolean.SelectedIndex = 2;
                    }
                }
                else
                {
                    myControl.cbxBoolean.SelectedIndex = 0;
                }
            }
            if (myControl.SelectedValueChanged != null && e.OldValue != e.NewValue)
            {
                myControl.SelectedValueChanged(myControl, new RoutedPropertyChangedEventArgs<bool?>(e.OldValue as bool?, e.NewValue as bool?));
            }
        }

        public BooleanPicker()
        {
            InitializeComponent();
        }

        private void cbxBoolean_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cbxBoolean != null)
            {
                switch (cbxBoolean.SelectedIndex)
                {
                    case 0:
                        this.SelectedValue = null;
                        break;
                    case 1:
                        this.SelectedValue = true;
                        break;
                    case 2:
                        this.SelectedValue = false;
                        break;
                }
            }
        }
    }
}
